<?php
/**
 * Created by PhpStorm.
 * User: chenx
 * Date: 18-3-25
 * Time: 下午9:50
 */

namespace common\service;


use common\components\HttpClient;
use common\models\Code;

class SmsService extends BaseService
{
    /**
     * 短信验证码入库
     * @param string $phone
     * @return string
     */
    public static function addSms($phone){
        $code = CommonService::random(4,1);
        $row['phone'] = $phone;
        $row['code'] = $code;
        $row['time'] = time();
        $row['status'] = 0;
        $row['client_ip'] = CommonService::getIP();
        $row['is_del'] = 0;
        $code_model = new Code();
        $code_model->setAttributes($row);
        $code_model->save();
        return $code;
    }

    /**
     * 发送短信验证码
     * @param string $mobile
     * @param $m_code
     * @return bool
     */
    public static function sendSms($mobile='', $m_code){
        if(!$mobile) return false;
        $message = '【一键拼团】提醒您，您的验证码是:'.$m_code.',验证码在5分钟后过期,请您及时验证，工作人员不会向您索要验证码，请勿向任何单位或个人泄露！';
        $data = [
            'un' => \Yii::$app->params['phone_code']['user'],
            'pw' => \Yii::$app->params['phone_code']['pwd'],
            'da' => $mobile,
            'sm' => bin2hex(iconv("UTF-8", "GB2312", $message)),
            'dc' => 15,
            'rd' => 0
        ];
        $resp = HttpClient::post(\Yii::$app->params['phone_code']['url'],$data);

        if (explode('=', $resp)[0] === 'id') return true;
        return false;
    }

}